(function(app){
	app
		.controller("photo_signCtrl",["$scope","myFactory",'$http','$stateParams','$interval','$state',"$q",'$timeout','$location','$ionicHistory',function($scope,myFactory,$http,$stateParams,$interval,$state,$q,$timeout,$location,$ionicHistory){
			//接收参数
			var itemId = $stateParams.itemId;//变更项目ID
			var chdrnum01 =  $stateParams.chdrnum01; //保单号
			$scope.chdrnum01=$stateParams.chdrnum01; //保单号
			var chdrcoy = $stateParams.chdrcoy; //保单公司号码
			//判断投保人被保人是否同一个人，是的话，即使更新了10变更项，也仍然不需要被保人签名 add by csf start
			var isSamePerson = $stateParams.isSamePerson;//判断投被保人同一个人
			//判断投保人被保人是否同一个人，是的话，即使更新了10变更项，也仍然不需要被保人签名 add by csf end
			$scope.signMainData=$stateParams.signMainData;
			var signMainData = $stateParams.signMainData;
			var strItemIds=signMainData.strItemIds;
			var signMid=signMainData.signMid;

			//页面数据
			$scope.signRule=signMainData.signRule;
			var signRule=signMainData.signRule;
			$scope.policy=signMainData.policy;
			
			var token=sessionStorage.getItem("token");

			$scope.data = {
				timeCon: '获取手机验证码',
				textFlag: true,
				timeSign: null
			};

			/******************页面部分显示逻辑处理begin**************/
			$scope.showPolicyHolderLbFlag=false;
			$scope.showInsuredLbFlag=false;
			$scope.showBenefiLbFlag=false;

			$scope.img_policyHolderSgFlag=false;
			$scope.img_insuredSgFlag=false;
			$scope.img_benefiSgFlag=false;

			var signContentId={//影像对应的contextid
				policyHolderSg:20,
				insuredSg:21,
				benefiSg:22
			}

			var valnum_temp="000000";
			var maxTime=180;//10;//实际业务：180s
			var curentId="";
			var timeOutSign="N";
			
			//S2018051403895_信易通人证合一及活体检测项目需求 add by rqyang 20180729 begin
			$scope.isSignOpenFlag=true;
			//S2018051403895_信易通人证合一及活体检测项目需求 add by rqyang 20180729 end
			
			//移动保全应用系统安全开发检查表 add by huanghk 20230802 start
			getInitCode();
			//移动保全应用系统安全开发检查表 add by huanghk 20230802 end

			//投保人签名
			if(signRule.policyHolder=='Y'){
				$scope.showPolicyHolderLbFlag=true;
				console.log("--->投保人签名");

				$("#img_policyHolderSg").attr('src','');//data:image/gif;base64,{{policyHolderSg}}
				$scope.img_policyHolderSgFlag=false;

				$("#photo_cover_20").css('display','block');
				$("#text_cover_20").css('display','block');
				$("#delImg_20").css('display','none');
			}

			//被保人签名
			if(signRule.insured=='Y'){
//S2018110706102 - 移动保全受理含“10-更改个人资料”的多项变更，客户签名留影缺失问题 add by csf 20181114  start  
				$scope.showInsuredLbFlag=true;
				console.log("--->被保险人签名");
				$("#img_insuredSg").attr('src','');
				$scope.img_insuredSgFlag=false;
				$("#photo_cover_21").css('display','block');
				$("#text_cover_21").css('display','block');
				$("#delImg_21").css('display','none');
			}
//			if(signRule.insured=='Y'){
//				var checkFlag=checkIsItemIdType("10");//检测是不是为更改资料信息变更，即变更项为10
//				if(checkFlag=="N"){
//					$scope.showInsuredLbFlag=true;
//					console.log("--->被保险人签名");
//					$("#img_insuredSg").attr('src','');
//					$scope.img_insuredSgFlag=false;
//					$("#photo_cover_21").css('display','block');
//					$("#text_cover_21").css('display','block');
//					$("#delImg_21").css('display','none');
//				}else{
//					var flag = sessionStorage.getItem("isChange_insured_item10");
//					//如果被保人信息没有被更改，则隐藏被保人的电子签名
//					var isManyItes = checkMany();
////					if(1==flag){
//					/**S2018110706102 - 移动保全受理含“10-更改个人资料”的多项变更，客户签名留影缺失问题 add by csf 20181114  start
//							对于多项变更项的处理,如果被保人信息没有被修改则判断是否为多项变更，是的话就显示被保人信息
//					*/
//						if(1==flag || isManyItes){
//					/** S2018110706102 - 移动保全受理含“10-更改个人资料”的多项变更，客户签名留影缺失问题 add by csf 20181114  end
//					 * 
//					 */
//						$scope.showInsuredLbFlag=true;
//						console.log("--->被保险人签名");
//						$("#img_insuredSg").attr('src','');
//						$scope.img_insuredSgFlag=false;
//						$("#photo_cover_21").css('display','block');
//						$("#text_cover_21").css('display','block');
//						$("#delImg_21").css('display','none');
//					}
//				}
//			}
			/**
			 * 根据被保人生日获取年龄
			 */
			function getAge(strBirthday){       
			    var returnAge;
			    var birthYear = strBirthday.substr(0,4);
			    var birthMonth = strBirthday.substr(4,2);
			    var birthDay = strBirthday.substr(6,2);
			    
			    d = new Date();
			    var nowYear = d.getFullYear();
			    var nowMonth = d.getMonth() + 1;
			    var nowDay = d.getDate();
			    
			    if(nowYear == birthYear){
			        returnAge = 0;//同年 则为0岁
			    }
			    else{
			        var ageDiff = nowYear - birthYear ; //年之差
			        if(ageDiff > 0){
			            if(nowMonth == birthMonth) {
			                var dayDiff = nowDay - birthDay;//日之差
			                if(dayDiff < 0){
			                    returnAge = ageDiff - 1;
			                }else{
			                    returnAge = ageDiff ;
			                }
			            }
			            else
			            {
			                var monthDiff = nowMonth - birthMonth;//月之差
			                if(monthDiff < 0)
			                    returnAge = ageDiff - 1;
			                else
			                    returnAge = ageDiff ;
			            }
			        }
			        else
			        {
			            returnAge = -1;
			        }
			    } 
			    return returnAge;
			
			}
			//判断被保人信息在界面上是否被更改,是的话，也需要被保人签名
			//判断被保人年两是否超过了18岁
			var flag = sessionStorage.getItem("isChange_insured_item10");
			var age = getAge(signMainData.policy.rnBirthday +"");
			//判断投保人被保人是否同一个人，是的话，即使更新了10变更项，也仍然不需要被保人签名 add by csf start
			if ( 1 == flag && age >= 18 && !isSamePerson){
				//判断投保人被保人是否同一个人，是的话，即使更新了10变更项，也仍然不需要被保人签名 add by csf end
				$scope.showInsuredLbFlag=true;
				console.log("--->被保险人签名");
				$("#img_insuredSg").attr('src','');
				$scope.img_insuredSgFlag=false;
				$("#photo_cover_21").css('display','block');
				$("#text_cover_21").css('display','block');
				$("#delImg_21").css('display','none');
			}
			//S2018110706102 - 移动保全受理含“10-更改个人资料”的多项变更，客户签名留影缺失问题 add by csf 20181114  end  
			//权益人签名
			if(signRule.benefi=='Y'){
				$scope.showBenefiLbFlag=true;
				console.log("--->权益人签名");

				$("#img_benefiSg").attr('src','');

				$scope.img_benefiSgFlag=false;

				$("#photo_cover_22").css('display','block');
				$("#text_cover_22").css('display','block');
				$("#delImg_22").css('display','none');
			}

			/******************页面部分显示逻辑处理end**************/

			//点击签名
			$scope.showPopupDialog = function(context_id){
				if($scope.isSignOpenFlag){
					$scope.isSignOpenFlag=false;
					//$(this).addClass("disabled");
					setTimeout(function() {
						$scope.isSignOpenFlag=true;
						//$(this).removeClass("disabled");
					}, 350);
				}else{
					return false;
				}
				
				console.log('调用信易通内核签名.......');
				if(context_id=='20'){
					var data = {
						title : '投保人（签名）',
						titleSpanFromOffset : '4',//4
						titleSpanToOffset : '5',//5
						singleWidth : '150',
						singleHeight : '75',
						businessType : '1',//1:投保人签名 2：被保人签名 0:风险提示语
						Identitycardnbr : $("#holderIDNo").val(),
						username : $("#holderNm").val(),
						nessesary : 'false',
						//template_serial : $("#policyNo").val()+"_01",
						template_serial :signMid,
						/*北京CA签名认证2.0版本  add by yangyan 20190903 start*/
						serverConfigName:'投保人签名',
						aloFlag:'Y',
						/*北京CA签名认证2.0版本  add by yangyan 20190903 end*/
						serverConfigRule : '1122'
					};
					
					var policyHolderSgTemp=$("#policyHolderSg").val();
					if(policyHolderSgTemp!=""){
						return false;
					}

					/****************测试数据*****************/
					var appVersionFlag = myFactory.getBrowserType();
					console.log("appVersionFlag:"+appVersionFlag);
					if(appVersionFlag=="Android"){
						//alert("Android");
					}else if(appVersionFlag=="IOS"){
						//alert("IOS");
					}else if(appVersionFlag=="Browser"){
						var testVal="R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7";
						$("#img_policyHolderSg").attr('src','data:image/gif;base64,'+testVal);
						$("#policyHolderSg").val(testVal);
						$("#encodedDataHolderSg").val("base64");//测试数据
						$("#img_policyHolderSg").css('display','inline');
						$("#photo_cover_20").css('display','none');
						$("#text_cover_20").css('display','none');
						$("#delImg_20").css('display','inline');
						return false;
					}else{
						alert("others");
					}

					var appVersionFlag = myFactory.getBrowserType();
					console.log("appVersionFlag:"+appVersionFlag);
					if(appVersionFlag=="Android"){
					}else if(appVersionFlag=="IOS"){
					}else if(appVersionFlag=="Browser"){

					}else{
					}
					/****************测试数据*****************/

					/*if(curentId!=""){
						curentId="";
					}
					curentId=context_id;
					cordova.sino.digitalSignature(callbackFunctionSign, data);*///引用新的js脚本文件
				}

				if(context_id=='21'){
					var data = {
						title : '被保险人（签名）',
						titleSpanFromOffset : '5',
						titleSpanToOffset : '6',
						singleWidth : '150',
						singleHeight : '75',
						businessType : '2',//1:投保人签名 2：被保人签名 0:风险提示语
						Identitycardnbr : $("#insuredIDNo").val(),
						username : $("#insuredNm").val(),
						nessesary : 'false',
						//template_serial : $("#policyNo").val()+"_02",
						template_serial :signMid,
						/*北京CA签名认证2.0版本  add by yangyan 20190903 start*/
						serverConfigName:'被保险人签名',
						aloFlag:'Y',
						/*北京CA签名认证2.0版本  add by yangyan 20190903 end*/
						serverConfigRule : '1124'
					};

					var insuredSgTemp=$("#insuredSg").val();
					if(insuredSgTemp!=""){
						return false;
					}

					var appVersionFlag = myFactory.getBrowserType();
					console.log("appVersionFlag:"+appVersionFlag);
					if(appVersionFlag=="Android"){
					}else if(appVersionFlag=="IOS"){
					}else if(appVersionFlag=="Browser"){
						var testVal="R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7";
						$("#img_insuredSg").attr('src','data:image/gif;base64,'+testVal);
						$("#insuredSg").val(testVal);
						$("#encodedDataInsuredSg").val("base64");//测试数据

						$("#img_insuredSg").css('display','inline');
						$("#photo_cover_21").css('display','none');
						$("#text_cover_21").css('display','none');
						$("#delImg_21").css('display','inline');
						return false;
					}else{
					}
					/****************测试数据*****************/

					/*if(curentId!=""){
						curentId="";
					}
					curentId=context_id;
					cordova.sino.digitalSignature(callbackFunctionSign, data);*/
				}

				if(context_id=='22'){
					var data = {
						title : '权益人（签名）',
						titleSpanFromOffset : '4',
						titleSpanToOffset : '5',
						singleWidth : '150',
						singleHeight : '75',
						businessType : '2',//1:投保人签名 2：被保人签名 0:风险提示语
						Identitycardnbr : $("#benefiNo").val(),
						username : $("#benefiNm").val(),
						nessesary : 'false',
						//template_serial : $("#policyNo").val()+"_02",
						template_serial :signMid,
						/*北京CA签名认证2.0版本  add by yangyan 20190903 start*/
						serverConfigName:'权益人签名',
						aloFlag:'Y',
						/*北京CA签名认证2.0版本  add by yangyan 20190903 end*/
						serverConfigRule : '1128'
					};

					var benefiSgTemp=$("#benefiSg").val();
					if(benefiSgTemp!=""){
						return false;
					}

					var appVersionFlag = myFactory.getBrowserType();
					console.log("appVersionFlag:"+appVersionFlag);
					if(appVersionFlag=="Android"){
					}else if(appVersionFlag=="IOS"){
					}else if(appVersionFlag=="Browser"){
						var testVal="R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7";
						$("#img_benefiSg").attr('src','data:image/gif;base64,'+testVal);
						$("#benefiSg").val(testVal);
						$("#encodedDataBenefiSg").val("base64");//测试数据
						$("#img_benefiSg").css('display','inline');
						$("#photo_cover_22").css('display','none');
						$("#text_cover_22").css('display','none');
						$("#delImg_22").css('display','inline');
						return false;
					}else{
					}
					/****************测试数据*****************/

				}
				
				if(curentId!=""){
					curentId="";
				}
				curentId=context_id;
				
				//S2018051403895_信易通人证合一及活体检测项目需求 add by rqyang 20180729 begin
				
				
				/*$("#InfoSubmit").addClass("disabled");
				$("#prev1,#prev2").addClass("disabled");*/
				/*if(!initFlag){
					isCommitted = false;
					//$("#prev1,#prev2").removeClass("disabled");					
					myFactory.alert("","初始化时失败，请返回上一步重试","info");
					myFactory.loadingHide();
					return;
				}*/
				//S2018051403895_信易通人证合一及活体检测项目需求 add by rqyang 20180729 end
				
				cordova.sino.digitalSignature(callbackFunctionSign, data);
			}

			//电子签名回调函数Test
			var callbackFunctionSign = function(result){
				var data = result.data;
				var val = data.signImg;//签名数据
				var signdata= data.signatureData;//加密数据
				
				
				/***************writeSignLog begin******************/
				var callXytParam="curentId="+curentId+",调用信易通方法：cordova.sino.digitalSignature(callbackFunctionSign, data)";
				var logParam={
						"opType":"sign",
						"curentPtId":callXytParam,
						"chdrnum":chdrnum01,
						"photoDataLog":data,
						"photoDataLogVal":val
				};
				$scope.writeSignLog(logParam);
				/***************writeSignLog end******************/
				
				
				//myFactory.alert('','触发了回调函数，得到数据分别如下：签名数据val='+val+',加密数据signdata='+signdata,'info');
				if(val==undefined || val==null || val==""){
					//如果结果是空的，则什么都不做，安卓端因为点击取消也会触发回调函数
				}else{
					if(curentId!=''){
						if(curentId=='20'){
							$("#img_policyHolderSg").css('display','inline');
							$("#photo_cover_"+curentId).css('display','none');
							$("#text_cover_"+curentId).css('display','none');
							document.getElementById("img_policyHolderSg").src="data:image/png;base64," + val;
							$("#policyHolderSg").val(val);
							//$("#encodedData").val(signdata);
							$("#encodedDataHolderSg").val(signdata);
							$("#delImg_"+curentId).css('display','inline');
						}
						if(curentId=='21'){
							$("#img_insuredSg").css('display','inline');
							$("#photo_cover_21").css('display','none');
							$("#text_cover_21").css('display','none');
							$("#img_insuredSg").attr('src','data:image/gif;base64,'+val);//data:image/gif;base64,{{policyHolderSg}}
							$("#insuredSg").val(val);
							//$("#encodedData").val(signdata);
							$("#encodedDataInsuredSg").val(signdata);
							$("#delImg_21").css('display','inline');
						}
						if(curentId=='22'){
							$("#img_benefiSg").css('display','inline');
							$("#photo_cover_22").css('display','none');
							$("#text_cover_22").css('display','none');
							$("#img_benefiSg").attr('src','data:image/gif;base64,'+val);//data:image/gif;base64,{{policyHolderSg}}
							$("#benefiSg").val(val);
							//$("#encodedData").val(signdata);
							$("#encodedDataBenefiSg").val(signdata);
							$("#delImg_22").css('display','inline');
						}
					}
					curentId='';
				}
			}

			//点击删除签名图片
			$scope.deleteSign = function(e,context_id){
				e.stopPropagation();
				if(context_id=='20'){
					//$scope.img_policyHolderSgFlag=false;
					$("#img_policyHolderSg").css('display','none');
					$("#img_policyHolderSg").attr('src','');
					$("#policyHolderSg").val("");
					$("#encodedDataHolderSg").val("");
				}

				if(context_id=='21'){
					$("#img_insuredSg").css('display','none');
					$("#img_insuredSg").attr('src','');
					$("#insuredSg").val("");
					$("#encodedDataInsuredSg").val("");
				}

				if(context_id=='22'){
					$("#img_benefiSg").css('display','none');
					$("#img_benefiSg").attr('src','');
					$("#benefiSg").val("");
					$("#encodedDataBenefiSg").val("");
				}

				$("#photo_cover_"+context_id).css('display','block');
				$("#text_cover_"+context_id).css('display','block');
				$("#delImg_"+context_id).css('display','none');
			}

			//签名照片控制
			$scope.signPhoto = function(){
				var flag = $("#signPhoto").attr('src');
				if(flag != ''){
					$("#photo_cover").css('display','none');
					$("#text_cover").css('display','none');
					$("#cancelImg").css('display','inline');
				}
			}

			//图片验证码
			function getInitCode(){
				/*var code = "";
				var codeLength = 4; //验证码的长度
				var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
					'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
					'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //所有候选组成验证码的字符，当然也可以用中文的
				for (var i = 0; i < codeLength; i++)
				{
					var charNum = Math.floor(Math.random() * 52);
					code += codeChars[charNum];
				}
				valnum_temp=code;
				return code;*/
				var checkCode = document.getElementById("checkCode");
				var timestamp=myFactory.getTimetamp();
				var sfis= "token-timestamp";
				var signStr="token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				$http({
					method: 'post',
					url: app.domain + "common/captchaImage.action",
					data:{'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						$scope.uuid = response.data.data.uuid;
						//code = response.data.data.code;
						var img = response.data.data.img;
						if (checkCode){
							//checkCode.className = "code";
							//checkCode.innerHTML = code;
							//$scope.code= code;
							checkCode.src="data:image/jpg;base64,"+img;
						}
						console.log(code);
					}else{
						myFactory.alert('','获取图片验证码失败！','info');
					}
				}, function errorCallback(response) {
					myFactory.alert('','获取图片验证码失败！','info');
				});
			}

			$scope.changeImg = function(id) {
				var code = "";
				var codeLength = 4; //验证码的长度
				var checkCode = document.getElementById("checkCode");
				/*var codeChars = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
					'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
					'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //所有候选组成验证码的字符，当然也可以用中文的
				for (var i = 0; i < codeLength; i++)
				{
					var charNum = Math.floor(Math.random() * 52);
					code += codeChars[charNum];
				}*/
							
				//移动保全应用系统安全开发检查表 add by huanghk 20230802 start
				getInitCode();
				//移动保全应用系统安全开发检查表 add by huanghk 20230802 end
				
				//开发测试直接赋值
				//$("#valnum").val(code);
			}

			//图片验证码校验
			$scope.validateCode = function(){
				var flag=false;
				//var inputCode = document.getElementById("inputCode").value;
				var valnum = $("#valnum").val();
				if (valnum.length <= 0){
					myFactory.alert('','请输入图片验证码！','info');
					$("#valnum").focus();
					return flag;
				} else if (valnum.length < 4) {
					myFactory.alert('','输入图片验证码有误，请重新输入！','info');
					$("#valnum").focus();
					return flag;
				/*} else if (valnum_temp.toUpperCase() != valnum.toUpperCase()){
					myFactory.alert('','输入图片验证码有误，请重新输入！','info');
					$("#valnum").focus();
					return flag;*/
				} else {
					flag=true;
				}
				return flag;
			}

			$scope.getValidateNum = function(){
				var telNo = $("#telNo").val();
				if(!telNo){
					myFactory.alert('','手机号码为空！请先办理通讯方式变更','info');
					return;
				}

				var validateCode=$scope.validateCode();
				if(!validateCode){
					return false;
				}
				
				myFactory.loadingShow();//显示加载圈
				var url ="common/getValidateNum.action";
				//移动保全应用系统安全开发检查表 add by huanghk 20230802 start
				var uuid = $scope.uuid;
				var valnum = $("#valnum").val().trim();
				var timestamp=myFactory.getTimetamp();
				var sfis= "telNo-valfrom-valnum-token-timestamp";
				var signStr="telNo="+telNo+"&valfrom="+uuid+"&valnum="+valnum+"&token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				$http({
					method: 'GET',
					url: app.domain + url,
					params: {"telNo":telNo, "valfrom":uuid, "valnum":valnum,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						//$("#lbtime").val("");
						var sendStatus = response.data.data.sendStatus;
						var codeTemp = response.data.data.code;
						//console.log("return phone sendStatus:"+sendStatus);
						//console.log("return phone codeSign:"+codeTemp);
						myFactory.loadingHide();
						if(codeTemp=='000000'){
							myFactory.alert('','输入图片验证码有误，请重新输入！','info');
						}else{
							$scope.startSignIterval();
							//text = eval(text);
							//$("#sbefore").hide();
							//$("#safter").show();
							//$("#send").addClass('ui-disabled');//屏蔽“获取验证码”按钮
							$("#vlData").val(codeTemp);
							//$("#code").val(codeTemp);//测试，直接在后台传递值
							/*$.confirm("UAT测试：是否自动填入手机验证码:"+codeTemp, "", function() {
								$("#code").val(codeTemp);//测试，直接在后台传递值
							});*/
							
							if(sendStatus=='-2'){
								myFactory.alert('','获取手机验证码发送异常！','info');
							}
							if(sendStatus=='3'){
								myFactory.alert('','获取手机验证码太频繁,请稍候再试！','info');
							}
							if(sendStatus=='10'){
								myFactory.alert('','获取手机验证码超过每小时限制次数,请稍后重试！','info');
							}
						}
						
					}
				}, function errorCallback(response) {
					myFactory.loadingHide();
					myFactory.alert('','获取手机验证码失败！','info');
				});
				//移动保全应用系统安全开发检查表 add by huanghk 20230802 end
			}

			//手机验证码倒计时180秒
			$scope.startSignIterval = function(){
				maxTime=180;//10;//180
				timeOutSign="N";
				$scope.data.textFlag = false;
				$scope.data.timeCon = "有效期："+maxTime+"S";
				$scope.data.timeSign = $interval(function(){
					//console.log("rest timeSign1:"+maxTime);
					$("#ipttime").val(maxTime);
					maxTime--;
					//console.log("rest timeSign2:"+maxTime);

					if (maxTime < 1) {
						$scope.data.timeCon = "获取手机验证码";
						$scope.data.textFlag = true;
						$interval.cancel($scope.data.timeSign);
					} else {
						$scope.data.timeCon = "有效期："+maxTime+"S";
					}

					if(maxTime==0){
						//if(timeStopSign=="N"){
							//myFactory.alert('','手机验证码已过期！请重新获取验证码','info');
							//jQuery("#send").removeClass('ui-disabled');
							//$("#ipttime").val(maxTime);
							//$scope.changeImg('valnumPic');//优化一下，过期不刷新，免得客户觉得又要多一次输入验证码
							//$("#valnum").val("");
							//stopIterval(timer);
						//}
						timeOutSign="Y";
						$("#ipttime").val(maxTime);
						return false;
					}
		        }, 1000);
			}

			//重新受理
			$scope.renew = function(){
				$interval.cancel($scope.data.timeSign);
				myFactory.renew();
			}
			//退出移动保全
			$scope.exit = function(){
				$interval.cancel($scope.data.timeSign);
				myFactory.exit();
			}
			//返回上一页
			$scope.goBack = function(){
				$interval.cancel($scope.data.timeSign);//返回时立即停止倒计时
				myFactory.goBack();
			}

			//保单详情
			$scope.showPolicyDetail = function(){
				modal('open','policyModalOnSiInput','policyWindowOnSiInput','policyCloseXOnSiInput');
				var timestamp=myFactory.getTimetamp();
				var sfis= "chdrnum-chdrcoy-token-timestamp";
				var signStr="chdrnum="+chdrnum01+"&chdrcoy="+chdrcoy+"&token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				//初始化查询订单详情
				var policyData;
				$http({
					method: 'GET',
					url: app.domain + 'query/restFindPolicyDetail.action',
					params: {'chdrnum': chdrnum01,'chdrcoy': chdrcoy,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						policyData = response.data.data;
						$scope.policyData = policyData;
						$scope.policyData.ptdate01=myFactory.DateTools($scope.policyData.ptdate01);
					}
				}, function errorCallback(response) {
					$.alert({
						title: '',
						text: '初始化查询订单详情失败!',
						onOK: function () {
							//点击确认
						}
					});
				});
			}

			//保单详情弹窗关闭
			$scope.policyCancelOnSiInput = function(){
				modal('close','policyModalOnSiInput','policyWindowOnSiInput','policyCloseXOnSiInput');
			}

			$scope.gotoSubmit = function () {
				myFactory.loadingShow();
				var imgCheck=submitCheck();
				console.log("imgCheck:"+imgCheck);
				if(!imgCheck){
					console.log("签名校验不通过");
					myFactory.loadingHide();
					return false;
				}
				console.log("签名校验通过");

				/**********************************************计时器结束处理begin**********************************************/
				//$interval.cancel($scope.data.timeSign);
				$scope.data.timeCon = "获取手机验证码";
				$scope.data.textFlag = true;
				$interval.cancel($scope.data.timeSign);//立即终止倒计时,避免出现滚动条转动的时候已经到时间临界点
				/*if(1==1){//Test
					myFactory.loadingHide();
					return false;
				}*/
				/**********************************************计时器结束处理end**********************************************/

				var isSign = $("#isSign").val();
				var policyHolderSg = $("#policyHolderSg").val();
				var insuredSg = $("#insuredSg").val();
				var benefiSg = $("#benefiSg").val();
				//var encodedData = $("#encodedData").val();
				var encodedDataHolderSg = $("#encodedDataHolderSg").val();
				var encodedDataInsuredSg = $("#encodedDataInsuredSg").val();
				var encodedDataBenefiSg = $("#encodedDataBenefiSg").val();

				var frmSign="img/gotoPhotoMain.action";
				var params={
					"isSign":isSign,
					"policyHolderSg":policyHolderSg,
					"insuredSg":insuredSg,
					"benefiSg":benefiSg,
					"encodedDataHolderSg":encodedDataHolderSg,
					"encodedDataInsuredSg":encodedDataInsuredSg,
					"encodedDataBenefiSg":encodedDataBenefiSg
				};
				var signItems={"signItems":params};

				var timestamp=myFactory.getTimetamp();
				var sfis= "token-timestamp";
				var signStr="token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				//$timeout(function(){myFactory.loadingHide();},3000);手机端网络不稳定，不采取固定3秒后取消加载框
				$http({
					method: 'post',
					url: app.domain + frmSign,
					data:{paramsMap:signItems,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						var photoMainData = response.data.data.photoMainData;
						if(photoMainData!=undefined && photoMainData!=null && photoMainData!=""){
							//终止数据，提供返回重新处理
							//$("#valnum").val();
							//$scope.data.timeCon = "获取手机验证码";
							//$scope.data.textFlag = true;
							$interval.cancel($scope.data.timeSign);//立即终止倒计时
							myFactory.loadingHide();
							$ionicHistory.clearCache().then(function(){
								$state.go('photo_main',{
									itemId:itemId,
									chdrnum01:chdrnum01,
									chdrcoy:chdrcoy,
									photoMainData:photoMainData,
									signMainData:signMainData,
									//判断投保人被保人是否同一个人，是的话，即使更新了10变更项，也仍然不需要被保人签名 add by csf start
									isSamePerson:isSamePerson
									//判断投保人被保人是否同一个人，是的话，即使更新了10变更项，也仍然不需要被保人签名 add by csf end
								});
							});
						}else{
							myFactory.loadingHide();
							myFactory.alert('','签名影像保存异常，请返回重试','info');
						}
					}else{
						myFactory.loadingHide();
						myFactory.alert('','系统没有响应，请返回重试','info');
					}
				}, function errorCallback(response) {
					myFactory.loadingHide();
					myFactory.alert('','访问后台失败，请返回重试','info');
				});
			}

			function submitCheck(){
				var policyHolderSg = $("#policyHolderSg");
				var insuredSg = $("#insuredSg");
				var benefiSg = $("#benefiSg");

				//投保人签名
				if(signRule.policyHolder=='Y'){
					if(!policyHolderSg.val()){
						myFactory.alert('','投保人签名不能为空！','info');
						return false
					}
				}

				//被保人签名
				if(signRule.insured=='Y'){
					var checkFlag=checkIsItemIdType("10");
					if(checkFlag=="N"){
						if(!insuredSg.val()){
							myFactory.alert('','被保险人签名不能为空！','info');
							return false
						}
					}else{
						var flag = sessionStorage.getItem("isChange_insured_item10");
						if(1==flag){
							if(!insuredSg.val()){
								myFactory.alert('','被保险人签名不能为空！','info');
								return false
							}
						}
					}
				} 
				
				//权益人签名
				if(signRule.benefi=='Y'){
					if(!benefiSg.val()){
						myFactory.alert('','受益人签名不能为空！','info');
						return false
					}
				}

				var validateCode=$scope.validateCode();
				if(!validateCode){
					return false;
				}

				if(!$("#code").val()){
					myFactory.alert('','请输入手机验证码!','info');
					return false;
				}
				var limitTime = $("#ipttime").val();
				if(parseInt(limitTime)<=0){
					if(timeOutSign=="Y"){
						myFactory.alert('','手机验证码已经过期!请重新获取验证码!','info');
						$scope.data.timeCon = "获取手机验证码";
						$scope.data.textFlag = true;
					}
					return false;
				}
				
				var codeSign=myFactory.hex($("#code").val());
				if(codeSign!=$("#vlData").val()){
					myFactory.alert('','手机验证码输入错误!','info');
					return false;
				}
				return true;
			}
		
			//S2018110706102 - 移动保全受理含“10-更改个人资料”的多项变更，客户签名留影缺失问题 add by csf 20181114  end
			function checkIsItemIdType(itemIdType) {
				var checkFlag="N";
				if ("" != strItemIds) {
					var itemIdTypeTemp="";
					var strItemIdsSplit = strItemIds.split(",");
					for(var k=0;k<strItemIdsSplit.length;k++){
						itemIdTypeTemp=strItemIdsSplit[k];
						if(itemIdTypeTemp==itemIdType){
							checkFlag="Y";
							break;
						}
					}
				}
				return checkFlag;
			}

			$scope.generateSigns = function () {
			//function generateSigns() {
				alert("generateSigns");

				/*$.holdReady(true);//阻止jquery的ready事件
				//如果是APP 版本则要等到 cordova加载完成后才能执行ready事件
				if(navigator.userAgent.match('SINO_([\\w])+_APP/([\\d.]+)')){
					alert("444");
					document.addEventListener('deviceready',function(){
						alert("555");
						console.log('cordova加载完成');
						cordova.sino = {};
						//初始化安卓端的数据
						cordova.exec(function(message) {
							cordova.sino.appData = message;
							$.holdReady(false);
						}, function(err) {
							cordova.sino.appData = null;
							$.holdReady(false);
						}, "SignaPlugin",appVersion==='IOS'?"initCordova":"1",[]);
					});
				}else{
					$.holdReady(false);
				}*/

				var data = {
					title : '投保人（签名）',
					titleSpanFromOffset : '4',
					titleSpanToOffset : '5',
					singleWidth : '150',
					singleHeight : '75',
					businessType : '1',//1:投保人签名 2：被保人签名 0:风险提示语
					Identitycardnbr : '1121212',
					username : '张三',
					nessesary : 'false',
					template_serial : '11222_111',
					serverConfigRule : '1122'
				};

				cordova.sino.digitalSignature(callbackFun_sign, data);
			}

			//电子签名函数
			var callbackFun_sign = function(result){
				var data = result.data;
				var val = data.signImg;//签名数据
				alert("测试："+val);
				document.getElementById("img").src="data:image/png;base64," + val;
			}

			$scope.takePhoto = function () {
				alert("takePhoto");
				var data = {
					width : '960',
					height : '720',
					mono : 'true',//bool 此选项无效
					quality : '50',//int 0~100 推荐85
					openFromGallery : 'false',//是否从相册选择照片
					businessType : '1'
				};
				cordova.sino.takePhoto(callBackFun_Camera, data);
			}

			//拍照回调
			var callBackFun_Camera=function(result){
				var data = result.data;
				var val = data.signImg;//拍照数据
				alert("测试："+val);
				document.getElementById("img").src="data:image/png;base64," + val;
			}

			$scope.sysBack = function () {
			//function sysBack(){
				alert("点击返回主系统");
				var data = {
					sessionTimeOut : 'No' //"Yes" Session超时 "No":系统正常的返回
				};
				cordova.sino.entryLocalSys(function(){}, data);
			}
			
			//图片预览
			$scope.photo_preview = function(id){
				$("#photo_preview2").show();
				var src = $("#"+id).attr("src");
				$("#photo_preview2 .big_photo").attr({"src":src});
				$("#photo_preview2").click(function(){
					$(this).hide();
				});
			}
			
			//签名日志
			$scope.writeSignLog = function(logParam){
				var photoItems={"photoItems":logParam};
				var token=sessionStorage.getItem("token");
				var timestamp=myFactory.getTimetamp();
				var sfis= "token-timestamp";
				var signStr="token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				$http({
					method: 'post',
					url: app.domain + 'img/writePhotoLog.action',
					data:{paramsMap:photoItems,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						console.log("writeSignLog ok");
					}
				}, function errorCallback(response) {
					console.log("writeSignLog error");
				});
			}

		}]);

		//指针弹窗
		app.directive('infoid',function(){
			return {
				restrict: 'EA',		//指明指令在DOM里面以什么形式被声明,EA.表示即可以是元素也可以是属性
				templateUrl: 'html/input/content_base_info.html'+app.clearCache,
				replace: true,		//设置解析后，DOM声明的指令是否消失
				link: function(scope,element,attrs){  //链接函数负责注册DOM事件和更新DOM,
					console.log('指令完成');
				}
			}
		});
		

})(app)